﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PrintingServer.ServerBase;
using PrintingServer;
using LogLib;
using IPrinting;

namespace PrintingServer.ClientCommands
{
    public class Init : ClientRequestPackCommand<PrintDataPackge>
    {
        public IPhotoPrint PrintApp = null;

        public string OutParams = "";

        public ClientRequestPackSession Session;

        public PhotoPrintingServer Server = null;

        public override void ExecuteCommand(ClientRequestPackSession session, PrintDataPackge pack)
        {
            try
            {
                Session = session;
                Server = session.AppServer as PhotoPrintingServer;
                Server.OnNewSessionRequestReceived(session, pack);
                if (!Server.PrintApps.ContainsKey(pack.Invoker))
                {
                    Log.WriteAsync("不存在的接口:" + pack.Invoker);
                    return;
                }
                PrintApp = Server.PrintApps[pack.Invoker];
                if (PrintApp == null)
                {
                    Log.WriteAsync("接口对象为空:" + pack.Invoker);
                    return;
                }
                string outstring = "";
                PrintApp.Init(pack.InParams, out outstring);
                if (PrintApp.Inited)
                {
                    OnInitOK(outstring);
                }
                else
                {
                    OnInitFailed(PrintApp.ErrorMessage, outstring);
                }
            }          
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
                Server.OnCatchException(session, PrintApp, PrintAction.Init, ex);
                return;
            }
        }

        protected void OnInitOK(string outParams)
        {
            PrintResponsePackge pack = new PrintResponsePackge(PrintApp.Name, PrintAction.Init);
            pack.Success = true;
            pack.Message = "";
            pack.Result = PrintResult.InitOK;
            pack.SetParams(outParams);
            if (Session.Connected)
            {
                Session.Send(pack);
            }            
            Server.ReportPrintingReponse(pack);
        }

        protected void OnInitFailed(string reasonMsg, string outParams)
        {
            PrintResponsePackge pack = new PrintResponsePackge(PrintApp.Name, PrintAction.Init);
            pack.Success = true;
            pack.Message = reasonMsg;
            pack.Result = PrintResult.InitFailed;
            pack.SetParams(outParams);
            if (Session.Connected)
            {
                Session.Send(pack);
            }       
            Server.ReportPrintingReponse(pack);
        }
    }
}
